import {
  Breadcrumb,
  Button,
  Card,
  DatePicker,
  Form,
  message,
  Modal,
  Radio,
  Select,
  Space,
  Table,
  Tag,
} from 'antd';
import { Link } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react/cjs/react.development';
import { getChannelAPI } from '../../api/channel';
import { getArticleListAPI, delArticleListAPI } from '../../api/article';
import errorSrc from 'assets/error.png';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
// 函数
const ArticleList = () => {
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  // 状态
  const [channelList, setChannelList] = useState([]);
  const [articleData, setArticleData] = useState({});
  // 挂载函数
  const loadArticles = async (params) => {
    // console.log('标识', page, per_page);
    const res = await getArticleListAPI(params);
    // console.log(res);
    setArticleData(res.data);
  };
  // HOOKS
  useEffect(() => {
    getChannelAPI().then((res) => {
      // console.log(res);
      setChannelList(res.data.channels);
    });
    loadArticles();
  }, []);
  // useRef
  const formDataRef = useRef(null);
  const pageInfoRef = useRef(null);
  // 筛选
  const handleSubmit = (val) => {
    console.log(val);
    const formDate = { ...val };
    if (val.status === -1) {
      delete formDate.status;
    }
    console.log(formDate);
    if (val.date) {
      const begin_pubdate = formDate.date[0].format('YYYY-MM-DD');
      const end_pubdate = formDate.date[1].format('YYYY-MM-DD');
      formDate.begin_pubdate = begin_pubdate;
      formDate.end_pubdate = end_pubdate;
      delete formDate.date;
    }
    formDataRef.current = formDate;
    console.log(formDate);
    loadArticles(formDate);
  };
  // 分页
  const handlePage = (page, pageSize) => {
    console.log({ ...formDataRef.current });
    pageInfoRef.current = { page, per_page: pageSize };
    loadArticles({
      page,
      per_page: pageSize,
      ...(formDataRef.current || {}),
    });
  };
  // 删除

  function delArticleList(id) {
    // console.log(pageInfoRef.current);
    // console.log(formDataRef.current);
    Modal.confirm({
      title: '删除',
      content: '是否删除文章',
      async onOk() {
        await delArticleListAPI(id);
        //  判断是否当页最后一条数据
        if (articleData.results.length === 1) {
          // 当页最后一条数据删除完毕页数减一 刷新

          const { page, per_page } = pageInfoRef.current;
          if (page === 1) {
            loadArticles({
              ...(pageInfoRef.current || {}),
              ...(formDataRef.current || {}),
            });
          } else {
            loadArticles({
              page: page - 1,
              per_page,
              ...(formDataRef.current || {}),
            });
          }
        } else {
          // 3. 重新请求刷新界面 🔔 加回查询参数
          loadArticles({
            ...(pageInfoRef.current || {}),
            ...(formDataRef.current || {}),
          });
        }
        // 4. 删除成功
        message.success('删除成功', 1);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(value) {
        if (!value.images.length) {
          return <img width={100} height={60} src={errorSrc} alt="" />;
        }
        return <img width={100} height={60} src={value.images[0]} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(value) {
        const info = articleStatus.find((item) => item.id === value);
        return <Tag color={info.color}> {info.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render(value, record, index) {
        // console.log(value === record);
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            ></Button>
            <Button
              type="primary"
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => delArticleList(record.id)}
            ></Button>
          </Space>
        );
      },
    },
  ];
  return (
    <div style={{ paddingTop: 24 }}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form
          name="basic"
          onFinish={handleSubmit}
          autoComplete="off"
          initialValues={{ status: -1, channel_id: 0 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Select style={{ width: 180 }} placeholder="请选择频道列表">
              {channelList.map((item) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="日期" name="date">
            <DatePicker.RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <h2>根据筛选条件共查询到 {articleData.total_count} 条结果：</h2>
        <Table
          columns={columns}
          dataSource={articleData.results}
          rowKey="id"
          pagination={{
            onChange: handlePage,
            position: ['bottomCenter'],
            current: articleData.page,
            pageSize: articleData.per_page,
            total: articleData.total_count,
          }}
        />
      </Card>
    </div>
  );
};
export default ArticleList;
